package com.hp.ecs.xqa.util;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import com.hp.ecs.xqa.util.exception.IoException;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FtlUtil {
	private static final String UTF_8 = "UTF-8";

	private static final Configuration CONFIG = createConfig();

	private static Configuration createConfig() {
		Configuration config = new Configuration();
		config.setEncoding(Locale.getDefault(), UTF_8);
		config.setClassForTemplateLoading(FtlUtil.class, "/template");
		return config;
	}

	public static String build(Object data, String ftlPath) {
		try {
			Template template = CONFIG.getTemplate(ftlPath);
			template.setEncoding(UTF_8);
			StringWriter writer = new StringWriter();
			final Map map = toMap(data);
			template.process(map, writer);
			return writer.toString();
		} catch (Exception e) {
			throw new IoException(e);
		}
	}

	public static String script(Object data, String ftlPath) {
		return build(data,"script/"+ftlPath);
	}
	
	private static Map toMap(Object data) {
		if (data instanceof Map) {
			return (Map)data;
		}
		Map map = new HashMap();
		map.put("r", data);
		return map;
	}

}
